package com.example.demoes.service.impl;

import com.example.demoes.entity.OmsOrder;
import com.example.demoes.service.OmsOrderTemplateService;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: rosszhang
 * @date: 2023/12/9 14:07
 * @description:
 **/
@Service
@RequiredArgsConstructor
public class OmsOrderTemplateServiceImpl implements OmsOrderTemplateService {

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public List<OmsOrder> getTemplateByMemberUsername(String memberUsername) {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                // 根据用户名查询
                .withQuery(QueryBuilders.queryStringQuery(memberUsername))
                .build();
        SearchHits<OmsOrder> search = elasticsearchRestTemplate.search(query, OmsOrder.class);
        List<SearchHit<OmsOrder>> searchHits = search.getSearchHits();
      /*
        一种：
        return searchHits.stream().map(item -> {
            OmsOrder content = item.getContent();
            return content;
        }).collect(Collectors.toList());  */

        /*
        二种：
        return searchHits.stream().map(item -> item.getContent()).collect(Collectors.toList());*/

        /* 三种： */
        return searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());

    }

    @Override
    public void deleteTemplateById(Long id) {
        OmsOrder omsOrder=new OmsOrder();
        omsOrder.setId(id);
        this.elasticsearchRestTemplate.delete(omsOrder);
    }

    @Override
    public long countTemplate() {
        NativeSearchQuery query = new NativeSearchQueryBuilder().build();
        return elasticsearchRestTemplate.count(query,OmsOrder.class);
    }
}
